package common.web.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.alibaba.fastjson.JSONObject;

import common.hibernate.service.BaseService;
import common.log.service.LogService;
import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.GroupRole;
import common.rbac.po.Role;
import common.rbac.po.RoleAuthority;
import common.util.JSONUtils;
import common.util.UUIDUtil;
import common.web.vo.Result;

@Controller
@RequestMapping("/system/role")
public class RoleAction extends MultiActionController {
	@Autowired
	@Qualifier("baseServiceImpl")
	protected BaseService baseService;
	
	@Autowired
	private LogService logService;

	@RequestMapping("/view/{id}")
	@ResponseBody
	public Result view(@PathVariable String id) {
		Role role = this.baseService.get(Role.class, id);
		if(null == role) {
			return Result.fail("组不存在");
		}
		Result result = Result.createResult(role);
		
		// 查询关联的权限
		RoleAuthority ra = new RoleAuthority();
		ra.setRoleId(role.getId());
		result.addMap("auths", this.baseService.findByExample(ra));
		return result;
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public Result list() {
		List<? extends Role> list = baseService.loadAll(Role.class);
		return Result.createResult(list);
	}
	

	@RequestMapping("/{editType}")
	@ResponseBody
	public Result save(@PathVariable String editType, @RequestBody JSONObject json) {
		Role role = JSONUtils.toJavaObject(json.getJSONObject("entity"), Role.class);
		List<RoleAuthority> grs = JSONUtils.toJavaObject(json.getJSONArray("auths"), RoleAuthority.class);
		if (null != role) {
			WebLog log = new WebLog(LogModule.ROLE, LogType.ADD, "操作失败");
			if("update".equals(editType)) {
				log.setType(LogType.UPDATE);
			}
			try {
				List<Object> deletes = new ArrayList<>();
				
				// 关联的查询出来一起删除
				RoleAuthority ra = new RoleAuthority();
				ra.setRoleId(role.getId());
				GroupRole gr = new GroupRole();
				gr.setRoleId(role.getId());
				
				// 删除关联部分
				deletes.addAll(baseService.findByExample(ra));
				deletes.addAll(baseService.findByExample(gr));
				
				if ("update".equals(editType)) {
					baseService.dbOperation(grs.toArray(), new Object[]{role}, deletes.toArray());
					
					log.setSuccess(MessageFormat.format("修改角色[{0}]成功!", role.getName()));
				} else if ("add".equals(editType)) {
					role.setId(UUIDUtil.createUuid());
					List<Object> saves = new ArrayList<Object>();
					saves.add(role);
					for (RoleAuthority roleAuth : grs) {
						roleAuth.setRoleId(role.getId());
					}
					saves.addAll(grs);
					baseService.dbOperation(saves.toArray(), null, deletes.toArray());
					baseService.save();
					
					log.setSuccess(MessageFormat.format("新增角色[{0}]成功!", role.getName()));
				}
			} catch (Exception e) {
				log.setFail(MessageFormat.format("操作角色[{0}]失败!", role.getName()));
				logger.error("", e);
				
				return Result.fail("数据错误，请刷新后重试");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}
	
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Result delete(@PathVariable String id) {
		Role load = baseService.load(Role.class, id);
		if(null != load) {
			
			WebLog log = new WebLog(LogModule.ROLE, LogType.DELETE, "操作失败");
			try {
				List<Object> deletes = new ArrayList<>();
				
				// 关联的查询出来一起删除
				RoleAuthority ra = new RoleAuthority();
				ra.setRoleId(load.getId());
				GroupRole gr = new GroupRole();
				gr.setRoleId(load.getId());
				
				// 删除关联部分
				deletes.addAll(baseService.findByExample(ra));
				deletes.addAll(baseService.findByExample(gr));
				deletes.add(load);
				
				baseService.delete(deletes.toArray());
				
				log.setSuccess(MessageFormat.format("删除角色[{0}]成功!", load.getName()));
			} catch (Exception e) {
				log.setFail(MessageFormat.format("删除角色[{0}]失败!", load.getName()));
				logger.error("", e);
				
				return Result.fail("删除失败");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("角色不存在");
		}
		return Result.SUCCESS;
	}
}
